// web/src/app/api/(learn)/course/[courseId]/chapters/[chapterId]/progress/route.ts
import {NextRequest, NextResponse} from "next/server";
import {currentUser} from "@/lib/auth";
import {db} from "@/lib/db";

export async function PUT(
    req: NextRequest,
    {params}: { params: { courseId: string; chapterId: string } }
) {
    try {
        const user = await currentUser()
        if (!user) return new NextResponse('Unauthorized', {status: 401})

        const {isCompleted} = await req.json()
        const userProgress = await db.userProgress.upsert({
            where: {
                userId_chapterId: {
                    userId: user.id!,
                    chapterId: params.chapterId
                }
            },
            update: {
                isCompleted
            },
            create: {
                userId: user.id!,
                chapterId: params.chapterId,
                isCompleted
            }
        })

        return NextResponse.json(userProgress)
    } catch (error) {
        console.error('[CHAPTER_ID_PROGRESS]', error)
        return new NextResponse('Internal Server Error', {status: 500})
    }
}